package com.whcoding.multithreading.thred;

/**
 * @program: spring-boot-learning
 * @description:
 * @author: whcoding
 * @create: 2022-06-10 17:07
 **/

/**
 * 两个线程交替打印0～100的奇偶数， 使用wait/notify关键字
 * <p>
 */
public class SynchroizedPrintOddEven2 {

	private static int count = 0;
	//当前线程必须拥有此对象的锁，才能调用某个对象的wait()方法能让当前线程阻塞，
	private static final Object lock = new Object();

	public static void main(String[] args) {
		new Thread(new TurningRunner(), "偶数").start();
		new Thread(new TurningRunner(), "奇数").start();
	}

	//拿到锁，我们就打印,一旦打印完唤醒其他线程就休眠
	static class TurningRunner implements Runnable {
		@Override
		public void run() {
			while (count <= 100) {
				synchronized (lock) {
					System.out.println(Thread.currentThread().getName() + ":" + count++);
					lock.notify();
					if (count <= 100) {
						try {
							//如果任务没结束，唤醒其他线程，自己休眠
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	

}